package com.ch04.ex47;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * Created by zc on 2016/2/19.
 */
public class Folderprocessor extends RecursiveTask<List<String>> {

    private static final long serialVersionUID = 6420887119679119739L;

    private String path;
    private String extension;

    public Folderprocessor(String path, String extension) {
        this.path = path;
        this.extension = extension;
    }

    @Override
    protected List<String> compute() {
        List<String> list = new ArrayList<>();

        List<Folderprocessor> tasks = new ArrayList<>();

        File file = new File(path);
        File contnts[] = file.listFiles();
        if(contnts!=null){
            for(int i=0; i<contnts.length; i++){
                if(contnts[i].isDirectory()){
                    Folderprocessor task = new Folderprocessor(contnts[i].getAbsolutePath(),extension);
                    task.fork();
                    tasks.add(task);
                } else {
                    if(checkFile(contnts[i].getName())){
                        list.add(contnts[i].getAbsolutePath());
                    }
                }
            }
        }

        if(tasks.size()>50){
            System.out.printf("%s: %d tasks ran.\n",
                    file.getAbsoluteFile(), tasks.size());
        }

        addResultsFromTasks(list, tasks);
        return list;
    }

    private void addResultsFromTasks(List<String> list, List<Folderprocessor> tasks) {
        for(Folderprocessor item: tasks){
            list.addAll(item.join());
        }
    }

    private boolean checkFile(String name) {
        return name.endsWith(extension);
    }
}
